package RaceTimer;

import java.util.Date;
import javax.microedition.rms.*;

public class RaceDataHelper {
    private static String recordStoreName = "MobileRaceTimer_Races";
    
    
    public static boolean saveRace(Race race) {
        RecordStore raceRecordStore = null;
        
        try {
            raceRecordStore = RecordStore.openRecordStore(recordStoreName, true);
            byte[] bytes = race.serializeResults().getBytes();
            raceRecordStore.addRecord(bytes, 0, bytes.length);
            return true;
        } catch(RecordStoreException ex) {
            return false;
        } finally {
            try {
                raceRecordStore.closeRecordStore();
            } catch (Exception e) {
                
            }
        }
    }
    
    public static StoredResult[] getStoredResutls() throws RecordStoreException {
        RecordStore raceRecordStore = null;
        
        try {
            raceRecordStore = RecordStore.openRecordStore(recordStoreName, true);
            StoredResult[] results = new StoredResult[raceRecordStore.getNumRecords()];
            
            StoredResult result;
            String resultString;
            String dateString;
            int i = 0;
            RecordEnumeration re = raceRecordStore.enumerateRecords( null, null, false);
            
            while(re.hasNextElement()){
                int recordId= re.nextRecordId();
                resultString = new String(re.nextRecord());
                dateString = resultString.substring(resultString.indexOf("[")+1,resultString.indexOf("]")-1);
                
                result = new StoredResult(recordId,dateString,resultString);
                results[i] = result;
                i++;
                return results;
            }
       
        } catch(RecordStoreException ex) {
            throw ex;
        } finally {
            try {
                raceRecordStore.closeRecordStore();
            } catch (Exception e) {
                
            }
        }
        return null;
    }
}
